﻿CREATE PROCEDURE [dbo].[s_Tracker_Car_Install]
	@TrackerRequestID int,
	@TrackerIDs varchar(8000)
AS

IF NOT EXISTS(SELECT * FROM t_TrackerRequest WHERE ID = @TrackerRequestID AND VIN > '')BEGIN
	IF @@TRANCOUNT > 0 ROLLBACK TRAN	RAISERROR('No VIN - No Tracker!',16,1) RETURN
END

IF dbo.RequestStatus_Attr__CanInstallTrackers(@TrackerRequestID,DEFAULT) = 0 BEGIN
	IF @@TRANCOUNT > 0 ROLLBACK TRAN
	DECLARE @StatusName sysname
	SELECT @StatusName = MenuName FROM t_Menu WHERE MenuID = dbo.MenuIDsByAttribute__CanInstallTrackers()
	RAISERROR('Must be in [%s] status to install tracker(s)!',16,1,@StatusName)
	RETURN
END

--SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN TRAN;

/**/EXEC sh_Debug_Print 's_Tracker_Car_Install <> INSERT INTO t_Tracker_Car(TrackerID,VIN,TechnicianID,TrackerRequestID)';
WITH Trackers(TrackerID)AS(
	SELECT Element AS TrackerID FROM Split(@TrackerIDs,',')
)
INSERT INTO t_Tracker_Car(TrackerID,VIN,TechnicianID,TrackerRequestID)
SELECT Trackers.TrackerID,tr.VIN,tt.TechnicianID,@TrackerRequestID FROM  Trackers
INNER JOIN t_Technician_Tracker tt ON tt.TrackerID = Trackers.TrackerID
CROSS JOIN t_TrackerRequest tr
WHERE tr.ID = @TrackerRequestID
/**/IF @@ERROR <> 0 BEGIN IF @@TRANCOUNT > 0 ROLLBACK TRAN RETURN END

/**/EXEC sh_Debug_Print 's_Tracker_Car_Install <> EXEC smenu_TrackerRequest_Send @TrackerRequestID,1,1'
EXEC smenu_TrackerRequest_Send @TrackerRequestID,1,1
/**/IF @@ERROR <> 0 BEGIN PRINT 'Error' IF @@TRANCOUNT > 0 ROLLBACK TRAN RETURN END

IF @@TRANCOUNT > 0 BEGIN
	PRINT 'COMMIT'
	COMMIT TRAN
END



